<template>
	<!-- 运营系统-剧集列表 -->
	<d2-container class="d-flex flex-column mod-sys__user">
		<template v-if="$hasPermission('playlet:playletEpisodes:index')">
			<el-dialog class="innerDialog" v-dialogDrag :close-on-click-modal="false" width="500px"
				:title="(playTitle||'')+'  下载进度'" :visible.sync="innerDownloadVisible" append-to-body>
				<div class="d-flex flex-column mr-10">
					<div class="d-flex mb-5" style="font-size: 15px;">下载中，请稍后...</div>
					<el-progress :text-inside="false" :stroke-width="18" text-color="#409eff"
						:percentage="downloadPercentage"></el-progress>
					<div style="height: 30px;"></div>
				</div>
			</el-dialog>
			<el-dialog class="videoPlayinnerDialog" v-dialogDrag @close="closeVideoDialogFn" width="650px"
				:visible.sync="innerPlayVisible" append-to-body>
				<div slot="title" class="d-flex a-center j-sb dialog-title">
					<span class="d-flex dialog-title-text font-weight" style="font-size: 17px;">{{playTitle||'视频'}}</span>
				</div>
				<div class="playerMain">
					<d-player class="dplayer" :options="videoOptions" ref="player"></d-player>
				</div>
			</el-dialog>
			<div class="d-flex j-sb" slot="header">
				<el-form class="d-flex b-s mt-2 mb-10" :inline="true" size="small" :model="dataForm"
					@keyup.enter.native="getTableList(true)" @submit.native.prevent>
					<el-form-item label="短剧名称">
						<el-input v-model="dataForm.keyword" placeholder="短剧名称" clearable />
					</el-form-item>
					<el-form-item label="集数">
						<el-input v-model="dataForm.name" @input="(v)=>(dataForm.name=handleNumber1(v))"
							placeholder="集数,请输入数字" clearable />
					</el-form-item>
					<el-form-item>
						<el-button icon="el-icon-search" type="primary" @click="getTableList(true)">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="success" icon="el-icon-circle-plus-outline"
							v-show="$hasPermission('playlet:playletEpisodes:create')"
							@click="addOrUpdateData()">添加剧集</el-button>
					</el-form-item>
					<!-- <el-form-item >
						<el-button icon="el-icon-s-check" type="warning" @click="checkExamine(1)">微信批量审核</el-button>
					</el-form-item> -->
				<!-- 	<el-form-item v-if="examineType == 2">
						<el-button icon="el-icon-s-check" type="info" @click="checkExamine(2)">抖音批量审核</el-button>
					</el-form-item> -->
				</el-form>
				<div class="d-flex">
					<vxe-toolbar ref="toolbarRef" custom :refresh="{ queryMethod: getTableList,code:'query'}"></vxe-toolbar>
				</div>
			</div>
			<div class="d-flex h-100 b-s flex-column">
				<div class="d-flex flex-1">
					<div class="overflow">
						<vxe-table ref="xTable" key="playletEpisodesTable" border height="100%" resizable :data="dataList" :loading="tableLoading"
							:checkbox-config="{checkMethod: CheckboxIsDisabled}"
							@checkbox-all="selectAllEvent"
							@checkbox-change="selectChangeEvent"
							:loading-config="{icon: 'vxe-icon-indicator roll', text: '正在拼命加载中...'}">
							<vxe-column width="100" field="id" title="ID" sortable align="center"></vxe-column>
							<vxe-column width="180" field="playlet_name" title="短剧名称" align="center"></vxe-column>
							<vxe-column width="180" field="play_url" title="在线预览" align="center">
								<template v-slot="{ row }">
									<a class="preview pointer" style="color:#1389ff"
										@click.stop="previewVideoFn(row)">预览</a>
								</template>
							</vxe-column>
							<vxe-column width="150" field="cover" title="封面图" align="center">
								<template v-slot="{ row }">
									<img class="pointer" width="80" height="auto" :src="row.cover" style="border-radius: 5px;"
										@click.stop="previewPicFn(row)">
								</template>
							</vxe-column>
							<vxe-column width="150" field="playlet_number_name" title="集数名称"
								align="center"></vxe-column>
							<vxe-column width="150" field="playlet_number" title="集数" sortable align="center"></vxe-column>
							<vxe-column width="150" field="amount" title="价格" sortable align="center"></vxe-column>
							<vxe-column width="150" field="likes_number" title="点赞数量" sortable align="center"></vxe-column>
							<vxe-column width="150" field="share_number" title="分享数量" sortable align="center"></vxe-column>
							<vxe-column width="150" field="created_at" title="创建时间" sortable align="center"></vxe-column>
							<vxe-column width="160" field="updated_at" title="修改时间" sortable cell-type="string"
								align="center"></vxe-column>
							<vxe-column title="操作" width="230" align="center" fixed="right">
								<template v-slot="{ row }">
									<el-button size="medium" round icon="el-icon-edit"
										v-show="$hasPermission('playlet:playletEpisodes:update')"
										@click="addOrUpdateData(row)" type="primary">修改</el-button>
									<el-button size="medium" round icon="el-icon-edit"
										v-show="$hasPermission('playlet:playletEpisodes:delete')"
										@click="deleteHandleSetter(row)" type="primary">删除</el-button>
								</template>
							</vxe-column>
							<template #empty>
								<div class="d-flex flex-row a-center j-center font-md">
									<div class="d-flex">
										暂时没有充值模板~
									</div>
								</div>
							</template>
						</vxe-table>
					</div>
				</div>
			</div>
			<!-- 分页 -->
			<div class="d-flex" slot="footer">
				<vxe-pager background size="medium" align="right" :border="false" :current-page="dataForm.page"
					:page-size="dataForm.pageSize" :total="total" :pageSizes="[20,50,100,150,200]"
					:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']"
					@page-change="handlePageChange">
				</vxe-pager>
			</div>
			<!-- 新增/修改弹窗 -->
			<episodes-add-or-update v-if="addOrUpdateVisible" ref="addOrUpdateDialog"
				@refreshDataList="getTableList"></episodes-add-or-update>
			<!-- 播放视频弹窗 -->
			<play-video v-if="videoVisible" ref="videoDialog"></play-video>
			<!-- 图片预览弹窗 -->
			<pic-preview v-if="picVisible" ref="picDialog"></pic-preview>
			<el-dialog title="重要提示" class="checkTipDialog" :visible.sync="checkTipVisible" width="600px" center>
				<span>{{examineType==1?'微信':'抖音'}}已选列表：</span>
				<ul class="data-list">
					<li v-for="(item,index) in records" :key="index" @click.stop="openVideo(item)">
						{{item.playlet_name+' '+item.playlet_number_name}}
					</li>
				</ul>
				<span slot="footer" class="dialog-footer">
					<el-button class="mr-10" @click="checkTipVisible = false">取 消</el-button>
					<el-button class="ml-10" type="primary" @click="submitExamine()">提交{{examineType==1?'微信':'抖音'}}审核</el-button>
				</span>
			</el-dialog>
		</template>
		<template v-else>
			<div class="d-flex a-center j-center h-100 b-s flex-column">
				<img class="d-flex b-s mt-2 mb-10" src="../../../public/image/download.png" alt="没有访问权限" style="width: 300px;">
				<div class="d-flex">抱歉，您没有访问权限</div>
			</div>
		</template>
	</d2-container>
</template>

<script>
	let that;
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		handleNumber1
	} from '@/libs/validate'
	import { Message,MessageBox } from 'element-ui'
	import mixinViewModule from '@/mixins/view-module'
	import EpisodesAddOrUpdate from './playletEpisodes-add-or-update'
	import PlayVideo from './playVideo'
	import PicPreview from './picPreview'
	import * as clipboard from 'clipboard-polyfill'
	import VueDPlayer from '@/libs/vue-dplayer';
	require("/src/assets/style/vue-dplayer.css");
	export default {
		mixins: [mixinViewModule],
		components: {
			'd-player': VueDPlayer,
			EpisodesAddOrUpdate,
			PlayVideo,
			PicPreview
		},
		data() {
			return {
				diycheck:false,
			
				tableLoading: false,
				handleNumber1,
				curent: 0,
				total: 0,
				curName: '',
				innerPlayVisible: false,
				records: [],
				checkIDArray: [],
				checkTipVisible: false,
				dataForm: {
					page: 1,
					pageSize: 20,
					keyword: '', //搜索
				},
				videoVisible: false,
				picVisible: false,
				// 增改
				addOrUpdateVisible: false,
				roleVisible: false,
				dataList: [],
				customColumns: [],
				playTitle: '',
				innerDownloadVisible: false, //是否显示下载视频进度
				downloadPercentage: 0,
				examineType:1,//1微信，2抖音
				videoOptions: {
					video: {
						url: '', //视频链接
						pic: '', //封面图
						thumbnails: '' //缩略图
					},
					theme: '#409eff', //主题色
					screenshot: true, //是否支持截图
					autoplay: true, //是否自动播放
					preload: 'auto', //预加载
					contextmenu: [{
							text: '下载视频',
							click: (e) => {
								this.downloadVideo();
							},
						},
						{
							text: '复制视频地址',
							click: (e) => {
								if (this.videoOptions.video.url) {
									this.copyText(this.videoOptions.video.url);
									return;
								}
								this.$message({
									message: '复制失败！视频地址为空！',
									type: 'error',
									duration: 1500
								})
							},
						},
					]
				},
			}
		},
		created() {
			if (this.$hasPermission('playlet:playletEpisodes:index')) {
				this.getTableList();
			}
		},
		watch: {},
		mounted() {
			that = this;
		},
		computed: {
			...mapState('d2admin/user', [
				'info'
			])
		},
		methods: {
			...mapMutations({
				pageInit: 'd2admin/page/init',
				headerSet: 'd2admin/menu/headerSet'
			}),
			diychange(){
				this.examineType = this.examineType==1?2:1;
				console.log(272,this.examineType)
			},
			//预览视频
			previewVideoFn(row) {
				this.videoVisible = true;
				this.$nextTick(() => {
					this.$refs.videoDialog.update(row.play_url||row.original_play_url, row.playlet_name + '  ' + row.playlet_number_name,
						row.cover);
				})
			},
			//预览图片
			previewPicFn(row) {
				this.picVisible = true;
				this.$nextTick(() => {
					this.$refs.picDialog.update(row.cover, row.playlet_name + '  ' + row.playlet_number_name +
						' 封面图');
				})
			},
			CheckboxIsDisabled({
				row
			}) {
				// console.log(row);
				return ((row.media_status == 0 || row.media_status == 2 || row.media_status == 4) && (row.is_upload == 1 ||row.is_upload == 4))
			},
			copyText(text) {
				console.log(text);
				if(!text) {
					return that.$message({message: '数据为空，无法复制！',type: 'error',duration: 1500})
				}
				clipboard.writeText(text).then(
					function() {
						that.$message({
							message: '复制成功！',
							type: 'success',
							duration: 1500
						})
					},
					function() {
						that.$message({
							message: '复制失败！',
							type: 'error',
							duration: 1500
						})
					}
				);
			},
			closeVideoDialogFn() {
				this.player = this.$refs.player.dp;
				console.log(this.player);
				if (this.player) {
					this.player.pause();
					this.player.seek(0);
				}
			},
			selectAllEvent({
				checked
			}) {
		
				this.records = this.$refs.xTable.getCheckboxRecords();
				console.log(330,this.records)
				this.checkIDArray = this.records.map(element => element.id);
				console.log(334,this.checkIDArray);
			},
			
			selectChangeEvent({
				checked
			}) {
				this.records = this.$refs.xTable.getCheckboxRecords();
				this.checkIDArray = this.records.map(element => element.id);
				console.log(this.checkIDArray);
			},
			openVideo(row) {
				console.log(row);
				this.playTitle = row.playlet_name + ('  ' + row.playlet_number_name);
				this.innerPlayVisible = true;
				this.videoOptions.video.url = row.play_url||row.original_play_url;
				this.videoOptions.video.pic = row.cover;
				this.$nextTick(() => {
					if (!this.player) {
						this.player = this.$refs.player.dp;
					}
					this.player.switchVideo({
						url: row.play_url||row.original_play_url,
						pic: row.cover
					});
					setTimeout(() => {
						this.player.play();
					}, 100)
				})
			},
			// 检查勾选
			async checkExamine(type) {
				this.examineType = type;
				console.log(this.checkIDArray.length);
				if (!this.checkIDArray.length) {
					return this.$message({
						message: '请先勾选下面的剧集！',
						type: 'error',
						duration: 1500
					})
				}
				this.checkTipVisible = true;
			},
			async submitExamine() {
				this.checkTipVisible = false
				const examineRes = await this.$axios.post('/api/playlet/episodes/examine', {
					ids: this.checkIDArray,
					type:this.examineType
				});
				this.$refs.xTable.clearCheckboxRow()
				if(Array.isArray(examineRes)){
					if(examineRes.length){
						let html_String = '';
						html_String+="<div style='height:350px;overflow:auto;'>"
						for (var i = 0; i < examineRes.length; i++) {
							if(examineRes[i]){
								html_String+=`<span>${examineRes[i]}</span></br>`
							}
						}
						html_String+='</div>'
						MessageBox.alert(html_String,{
							title:'结果提示',
							dangerouslyUseHTMLString: true
						})
					}
				}
				console.log(examineRes);
			},
			async getTableList(init=false) {
				if(init&&typeof init =='boolean'){
					this.dataForm.page = 1;
				}
				this.tableLoading = true;
				const tableRes = await this.$axios.get('/api/playlet/episodes?' + this.$qs.stringify(this.dataForm));
				this.tableLoading = false;
				this.dataList = tableRes.data;
				console.log(403,this.dataList);
				this.total = tableRes.total;
			},
			async downloadVideo() {
				this.innerDownloadVisible = true;
				if (this.downloadPercentage != 0) {
					that.$message({
						message: `请等待${this.playTitle}下载完`,
						type: 'error',
						customClass: 'messageClass',
						duration: 2000,
					})
					this.innerDownloadVisible = true;
					return
				}
				let play_url = (this.videoOptions.video.url).replace("http://", "https://"),
					download_name = this.playTitle;
				try {
					let x = new XMLHttpRequest();
					x.open("GET", play_url, true);
					x.addEventListener("progress", function(evt) {
						if (evt.lengthComputable) {
							let percentComplete = evt.loaded / evt.total;
							that.downloadPercentage = Math.floor(percentComplete * 100);
							if (that.downloadPercentage == 100) {
								that.innerDownloadVisible = false;
								that.downloadPercentage = 0;
								that.$message({
									message: `${that.playTitle||'视频'}下载成功！`,
									type: 'success',
									duration: 2000
								})
							}
						}
					}, false);
					x.responseType = 'blob';
					x.onload = function(e) {
						//会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
						let url = window.URL.createObjectURL(x.response),
							a = document.createElement('a');
						a.href = url
						a.download = download_name;
						a.click();
						a.remove();
					}
					x.send();
				} catch (error) {
					that.innerDownloadVisible = false;
					that.downloadPercentage = 0;
					that.$message({
						message: '下载视频失败！',
						type: 'error',
						duration: 2000,
					})
					console.error(error);
				}
			},
			//新增/修改弹窗
			async addOrUpdateData(row) {
				console.log(row)
				this.addOrUpdateVisible = true;
				if (typeof row == 'object' && row != null) {
					// this.curName = row.real_name;
					const id = row.id;
					const userRes = await this.$axios.get(`/api/playlet/episodes/update/${id}`, {});
					this.$nextTick(() => {
						this.$refs.addOrUpdateDialog.playTitle = row.playlet_name + '  ' + row
							.playlet_number_name;
						this.$refs.addOrUpdateDialog.playId = id;
						this.$refs.addOrUpdateDialog.update(userRes);
					})
				} else {
					this.$nextTick(() => {
						this.$refs.addOrUpdateDialog.playId = null;
						this.$refs.addOrUpdateDialog.init()
					})
				}
			},
			// 删除
			deleteHandleSetter(row) {
				this.$confirm(this.$t('public.prompt.info', {
					handle: this.$t('views.public.delete')
				}), this.$t('public.prompt.title'), {
					confirmButtonText: this.$t('views.public.confirm'),
					cancelButtonText: this.$t('views.public.cancel'),
					type: 'warning'
				}).then(() => {
					this.$axios.delete(`/api/playlet/episodes/delete/${row.id}`, {}).then(res => {
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 500,
							onClose: () => {
								this.getTableList()
							}
						})
					}).catch(() => {})
				}).catch(() => {})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.successTag{
		background-color: #CAF0BA;
		color: #376F1F;
	}
	.warnTag{
		background-color: #fff1dc;
		color: #e6a23c;
	}
	.checkTipDialog :deep(.el-dialog__body) {
		padding: 5px 25px 0px 25px;
	}
	.videoPlayinnerDialog{
		.dialog-title{
			min-height: 48px;
			padding: 0px 60px 0px 20px;
			background-color: #000000;
			.dialog-title-text{
				color: #ffffff;
				font-size: 17px;
			}
		}
		:deep(.el-dialog__header) {
			padding: 0px !important;
			background-color: rgba(0, 0, 0, 0.9);
		}
		:deep(.el-dialog__body) {
			padding: 0px !important;
		}
		:deep(.el-dialog__headerbtn) {
			width: 60px;
			height: 42px;
			font-size: 25px !important;
			top: 0px;
			right: 0px;
			background-color: rgba(255, 255, 255, 0.05);
		}
	}
	.dplayer {
		height: 450px;
	}

	.checkTipDialog {
		.data-list {
			min-height: 200px;
			max-height: 450px;
			overflow-y: auto;
			padding: 0px;
			text-indent: 10px;
			margin: 5px 0px 0px 0px;
			list-style-type: none;

			li {
				cursor: pointer;
				border-radius: 6px;
				padding: 10px 0px 10px 0px;
			}

			li:hover {
				background-color: #f1f1f1;
				color: #409EFF;
			}
		}
	}
</style>